// src/router/index.js
import { createRouter, createWebHistory } from "vue-router";
import type { Router, RouteRecordRaw } from "vue-router";
// 动态导入模块路由
const modulesRouter: any = import.meta.glob("../apps/**/router/index.ts", {
  eager: true,
  import: "default",
});
// console.log("动态导入的模块路由", modulesRouter);
const pathList = new Set();
const allModuleRouter = new Set();
for (const key in modulesRouter) {
  for (let i = 0; i < modulesRouter[key].length; i++) {
    allModuleRouter.add(modulesRouter[key][i]);
  }
}
// console.log("动态导入的模块路由", allModuleRouter);
// 动态导入模块路由

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    component: () => import("../core/index.vue"),
    meta: { title: "首页" },
    children: [...allModuleRouter] as RouteRecordRaw[],
  },
];
/**
 * 将路由树数据转换为路径列表
 *
 * @param routes 路由树数据数组
 */
function routerTreeDataToPathList(routes: any[]) {
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i];
    if (route.children && route.children.length) {
      pathList.add(route.path);
      routerTreeDataToPathList(route.children);
    } else {
      pathList.add(route.path);
    }
  }
}
routerTreeDataToPathList(routes);
// console.log("最终的路由数据", routes);
// console.log("最终的路由列表", pathList);
/**
 * 通用守卫配置
 * @param router
 */
function setupCommonGuard(router: Router) {
  // 记录已经加载的页面

  router.beforeEach(async (to) => {
    // console.log("beforeEach", to);
    if (!pathList.has(to.path)) {
      console.log("路由文件中没有配置该路由，请检查");
      return false;
    }
  });
}

/**
 * 项目守卫配置
 * @param router
 */
function createRouterGuard(router: Router) {
  /** 通用 */
  setupCommonGuard(router);
  /** 权限访问 */
  // setupAccessGuard(router);
}

const router = createRouter({
  history: createWebHistory(),
  routes,
});
// 创建路由守卫
createRouterGuard(router);
export default router;
